<template>
  <div class="seed-table mc-table">
    <el-table
      v-loading="loading"
      @row-click="rowClick"
      width="100%"
      stripe
      height="100%"
      border
      size="mini"
      :data="tableData"
      style="width: 100%">


      <el-table-column type="expand">
        <template slot-scope="props">
          <expert-list @expertDetail="expertDetail" :clt-id="props.row.cltResultId"></expert-list>
        </template>
      </el-table-column>

      <el-table-column type="index" width="50" label="序号"/>

      <el-table-column prop="germplasmId" label="编号">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.germplasmId" placement="top-start">
            <div class="s-t-item">{{ scope.row.germplasmId }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="nickName" label="采集人">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.nickName" placement="top-start">
            <div class="s-t-item">{{ scope.row.nickName }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="location" label="采集地点">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.location" placement="top-start">
            <div class="s-t-item">{{ scope.row.location }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="collectionTime" label="采集时间">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.contractSealTime" placement="top-start">
            <div class="s-t-item">{{ parseTime(scope.row.contractSealTime, '{y}-{m}-{d}') }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="elecation" label="海拔">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark"
                      :content="scope.row.elecation == null ? '' : scope.row.elecation.toString()"
                      placement="top-start">
            <div class="s-t-item">{{ scope.row.elecation }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="niche" label="生境">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.niche" placement="top-start">
            <div class="s-t-item">{{ scope.row.niche }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="type" label="状态">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.type" placement="top-start">
            <div class="s-t-item">
              {{selectDictLabel([{dictValue:0,dictLabel:'未鉴定'},{dictValue:1,dictLabel:'已鉴定'},{dictValue:2,dictLabel:'已化验'},{dictValue:3,dictLabel:'已入库'}],
              scope.row.type )}}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300px">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            class="grass-flow-table-button"
            @click="setCurrentType(O_TYPES.AUT, scope.row.cltResultId, scope.row.germplasmId)"
          >鉴定
          </el-button>
          <el-button
            icon="el-icon-edit"
            class="grass-flow-table-button"
            @click="setCurrentType(O_TYPES.ASS, scope.row.cltResultId, scope.row.germplasmId)"
            :disabled="scope.row.type === '0'"
          >化验
          </el-button>
          <el-button
            icon="el-icon-edit"
            class="grass-flow-table-button"
            @click="setCurrentType(O_TYPES.STO, scope.row.cltResultId, scope.row.germplasmId)"
            :disabled="scope.row.type === '0' ||scope.row.type === '1' "
          >入库
          </el-button>
        </template>
      </el-table-column>

    </el-table>


    <lark-card border :x="500" body-height="480px" :body-width="'500px'" v-if="open" :hidden="!open"
               @closeAction="open = !open"
               :card-title="cardTile" draggable
               :radius="false">
      <el-scrollbar>
        <div class="seed-lab-body" style="padding: 10px 5px">

          <!--     鉴定     -->
          <el-form ref="edit-lab-form" :model="autForm" label-width="100px" :rules="autRules"
                   v-if="currentType === O_TYPES.AUT">

            <el-form-item label="名称" prop="name">

              <el-autocomplete
                v-model="autForm.name"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                @select="handleSelect"
              ></el-autocomplete>

            </el-form-item>

            <el-form-item label="学名" prop="scientificName">
              <el-input v-model="autForm.scientificName" placeholder="请输入学名 "/>
            </el-form-item>


            <el-form-item label="科名" prop="familyName">
              <el-select v-model="autForm.familyName" filterable allow-create placeholder="请选择">
                <el-option
                  v-for="item in familyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="属名" prop="categoryName">
              <el-select v-model="autForm.categoryName" filterable allow-create placeholder="请选择">
                <el-option
                  v-for="item in categoryList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="鉴定人" prop="userId">
              <el-select v-model="autForm.userId" filterable placeholder="请选择">
                <el-option
                  v-for="item in userList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="鉴定时间" prop="authenticateTime">
              <el-date-picker
                v-model="autForm.authenticateTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="autForm.remark"/>
            </el-form-item>

          </el-form>


          <!--     化验     -->
          <el-form ref="edit-lab-form" :model="assForm" label-width="100px" :rules="assRules"
                   v-if="currentType === O_TYPES.ASS">

          </el-form>

          <!--     入库     -->
          <el-form ref="edit-lab-form" :model="stoForm" label-width="100px" :rules="stoRules"
                   v-if="currentType === O_TYPES.STO">

          </el-form>

          <div class="edit-lab-submit">
            <el-button @click="saveBtn">{{cardTile}}</el-button>
          </div>

        </div>
      </el-scrollbar>
    </lark-card>


  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, watch, computed } from '@vue/composition-api'
  import { addLab, autAdd, editLab, getName, getProList, qualification } from '@/api/industry/lab'
  import { parseTime } from '@/utils/mc'
  import router from '@/router'
  import expertList from '@/components/ServiceComponents/expertList/index'

  export default {
    name: 'zzTable',
    props: {
      tableData: {
        type: Array,
        default: () => []
      },
      loading: {
        type: Boolean,
        default: false
      },

      labId: {
        type: [Number, String],
        default: ''
      },
      queryType: {
        type: [Number, String],
        default: null
      },
      pageNum: {
        type: [Number, String],
        default: null
      },
      pageSize: {
        type: [Number, String],
        default: null
      },
      showType: {
        type: [Number, String],
        default: null
      },
      proId: {
        type: [Number, String],
        default: null
      }
    },
    components: {
      expertList
    },
    setup(props, content) {

      const O_TYPES = {
        AUT: 'authenticate',
        ASS: 'assay',
        STO: 'storage'
      }

      //  鉴定
      const authenticate = async() => {
        let { autForm } = data
        await autAdd(autForm)
      }

      //  化验
      const assay = () => {
      }

      //  入库
      const storage = () => {
      }

      let data = reactive({
        O_TYPES,
        authenticate,
        assay,
        storage,
        open: false,
        cardTile: '',
        currentType: '',

        categoryList: [],      //  属名list
        familyList: [],        //  科名
        userList: [],          //  鉴定人

        autForm: {
          cltId: null,      // cltResultId
          scientificName: null,   //学名
          categoryName: null,    //  属名
          userId: null,       // 鉴定人id
          authenticateTime: null,//鉴定时间
          familyName: null,   //  科名
          name: null,  //  名称
          remark: ''   //备注
        },
        autRules: {
          scientificName: [
            { required: true, message: '学名不能为空', trigger: 'blur' }
          ],
          categoryName: [
            { required: true, message: '属名不能为空', trigger: 'blur' }
          ],
          userId: [
            { required: true, message: '鉴定人不能为空', trigger: 'blur' }
          ],
          authenticateTime: [
            { required: true, message: '鉴定时间不能为空', trigger: 'blur' }
          ],
          familyName: [
            { required: true, message: '科名不能为空', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ]
        },

        assForm: {
          cltId: null      // cltResultId
        },
        assRules: {},

        stoForm: {
          cltId: null      // cltResultId
        },
        stoRules: {}
      })

      const reset = () => {
        let { currentType } = data
        if (!currentType || currentType === '') return

        switch (currentType) {
          case O_TYPES.AUT:
            data.autForm = {
              cltId: null,      // cltResultId
              scientificName: null,   //学名
              categoryName: null,    //  属名
              userId: null,       // 鉴定人id
              authenticateTime: null,//鉴定时间
              familyName: null,   //  科名
              name: null,  //  名称
              remark: ''   //备注
            }
            break
          case O_TYPES.ASS:
            data.assForm = {}
            break
          case O_TYPES.STO:
            data.stoForm = {}
            break
        }

      }

      const saveBtn = () => {
        let { currentType } = data
        if (!currentType || currentType === '') return
        content.refs['edit-lab-form'].validate(async valid => {
          if (!valid) return
          await data[currentType]()
          reset()
          data.open = false
          content.emit('getData', {})
        })
      }

      const setCurrentType = (type, cltId, germplasmId) => {
        reset()
        data.currentType = type
        let { labId, pageNum, pageSize, queryType, proId, showType } = props
        switch (type) {
          case O_TYPES.AUT:
            data.cardTile = '鉴定'
            data.autForm.cltId = cltId
            data.open = true
            break
          case O_TYPES.ASS:
            data.open = false
            data.cardTile = '化验'
            data.assForm.cltId = cltId
            router.push({
              path: '/zza',
              query: { cltId, germplasmId, labId, pageNum, pageSize, queryType, proId, showType }
            })
            break
          case O_TYPES.STO:
            data.open = false
            data.cardTile = '入库'
            data.stoForm.cltId = cltId
            router.push({
              path: '/zzs',
              query: { cltId, germplasmId, labId, pageNum, pageSize, queryType, proId, showType }
            })
            break
        }
      }

      const rowClick = (row, column, event) => {
        content.emit('rowClick', { row, column, event })
      }

      const querySearchAsync = (queryString, cb) => {
        if (!queryString || queryString === '') {
          cb([])
        } else {
          getName(queryString).then(res => {
            cb(res.data.map(item => {
              let { name, family, district, latinName, latinFamily, latinDistrict } = item
              return { value: name, family, district, latinName, latinDistrict, latinFamily }
            }))
          })
        }
      }

      const handleSelect = item => {
        let { family, district, latinName, latinDistrict, latinFamily } = item
        data.autForm.scientificName = latinName
        data.autForm.categoryName = `${district} ${latinDistrict}`
        data.autForm.familyName = `${family} ${latinFamily}`
      }

      //  获取属名列表
      const getCategoryList = () => {
        qualification('district').then(res => {
          data.categoryList = res.data.map(item => {
            return { label: item, value: item }
          })
        })
      }

      //  获取科名列表
      const getFamilyList = () => {
        qualification('family').then(res => {
          data.familyList = res.data.map(item => {
            return { label: item, value: item }
          })
        })
      }

      //  获取鉴定人列表
      const getUserList = () => {
        getProList().then(res => {
          data.userList = res.data.map(item => {
            let { id: value, name: label } = item
            return { value, label }
          })
        })
      }

      const expertDetail = proId => {
        content.emit('expertDetail', { proId, type: 2 })
      }

      getCategoryList()
      getFamilyList()
      getUserList()

      return { ...toRefs(data), rowClick, saveBtn, setCurrentType, querySearchAsync, handleSelect, expertDetail }
    }
  }
</script>

<style lang="scss">
  .seed-table {
    height: 100%;
    width: 100%;

    .el-table {
      .el-table__body-wrapper {
        .el-table__body {
          .el-table__row {
            .cell {
              .s-t-item {
                width: 100%;
                height: 100%;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
          }
        }
      }
    }

  }

  .seed-lab-body {
    height: 470px;

    .edit-lab-submit {
      position: absolute;
      right: 20px;
      bottom: 10px;
    }
  }
</style>
